package com.example.medioplayer;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;

/**
 * Created by 快手 on 2017/7/3.
 */

public class CounterView extends View implements View.OnClickListener {
    private Paint mPaint;
    private Rect mRect;
    private int mCount = 0;//计数器
    private final String TAG = "CounterView >>";
    private String text = "";
    private int textSize = 30;
    private int textColor;

    public CounterView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CounterView);
        int count = typedArray.getIndexCount();
        for (int i = 0; i < count; ++i) {
            int name = typedArray.getIndex(i);
            switch (name) {
                case R.styleable.CounterView_text:
                    text = typedArray.getString(name);
                    break;
                case R.styleable.CounterView_color:
                    textColor = typedArray.getColor(name, Color.BLACK);
                    break;
                case R.styleable.CounterView_size:
                    textSize = typedArray.getDimensionPixelSize(name, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));
                    break;
            }
        }
        typedArray.recycle();

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mRect = new Rect();
        setOnClickListener(this);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPaint.setColor(Color.BLUE);
        //绘制视图
        canvas.drawRect(0, 0, getWidth(), getHeight(), mPaint);
        mPaint.setColor(textColor);
        mPaint.setTextSize(textSize);
//        String str = String.valueOf(mCount);
        //获取文字的宽和高
        mPaint.getTextBounds(text, 0, text.length(), mRect);
        float textWidth = mRect.width();
        float textHeight = mRect.height();
        //绘字制符串
        canvas.drawText(text, getWidth() / 2 - textWidth / 2, getHeight() / 2 + textHeight / 2, mPaint);
        Log.i(TAG, "" + getWidth() + "/n" + getHeight() + "/n" + textWidth + "/n" + textHeight);
    }

    @Override
    public void onClick(View v) {
        try {
            mCount = Integer.parseInt(text);
            text = ++mCount + "";
        } catch (Exception e) {

        }
        invalidate();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    }
}
